<!--
 * @Descripttion: 
 * @version: 
 * @Author: lihk
 * @Date: 2024-01-03 11:21:40
 * @LastEditors: lihk
 * @LastEditTime: 2024-01-06 16:51:11
-->
<template>
  <view class="content">
    <LfHeader :title="`专家问诊 (${userInfo.lastName +userInfo.firstName})`"></LfHeader>
    <!-- <Voice/> -->
    <view class="chat-container" ref="container">
      <Scrollview ref="scrollview" :scrollTop='scrollTop' :triggered='triggered' :data='messages' @loadMore="loadMore" :headUrl='{
      right:this.professorInfo.headUrl,
      left:this.userInfo.headUrl
    }' @previewImage='previewImage'></Scrollview>
      <view class="input-container">
        <view @click="isInput =!isInput">
          <img v-if="isInput" src="../../static/keyboard.png" alt="">
          <img v-else src="../../static/voice.png" alt="">
        </view>
        <view class="chat-input">
          <input v-if="isInput" v-model="newMessage" :focus="focusState" @confirm="sendMessage(newMessage)" />
          <view class="voice flex-cc" v-else>
            <LfVoice @voice='getVoice'></LfVoice>
          </view>
        </view>
        <LfUpload @url='getUrl'>
          <img src="../../static/picture.png" alt="">
        </LfUpload>
        <button v-if="isInput&&newMessage" class="send-button flex-cc" @click.stop="sendMessage(newMessage)">发送</button>
      </view>
    </view>
    <LfPopup :visible="previewImageVisible" @close="previewImageVisible=!previewImageVisible" position="center" :isContainer='false'>
      <!-- 弹窗内容 -->
      <view>
        <img style="width: 100%;" :src="previewImageUrl" alt="">
      </view>
    </LfPopup>
  </view>

</template>

<script>
import { getProfessorInfo, getUserInfo } from '../../utils/http';
import { getLocalStorage, isShowTime, setLocalStorage, showTime, initCache } from './index'
import Scrollview from './scrollView.vue'
import Voice from '../../components/voice.vue'
export default {
  components: {
    Scrollview,
    Voice
  },
  data () {
    return {
      scrollTop: 100,
      messages: [],
      newMessage: '',
      sessionInfo: {},
      triggered: false,
      userInfo: {},
      professorInfo: {},
      isInput: true,
      previewImageUrl: '',
      previewImageVisible: false,
      focusState: false
    };
  },
  async created () {
    //获取vuex的数据
    this.sessionInfo = this.$route?.query
    await this.connect()
    this.getInfo()
    initCache()
  },
  methods: {
    getVoice (e) {
      const voice = e.voice + ';' + e.time
      console.log("🚀 ~ file: chat.vue:92 ~ getVoice ~ voice:", voice)
      this.sendMessage(voice, 'img')
    },
    async getInfo () {
      const { data } = await getUserInfo(this.sessionInfo.userId)
      const { data: data2 } = await getProfessorInfo(this.sessionInfo.professorId)
      this.userInfo = data
      this.professorInfo = data2
    },
    loadMore () {
      const res = getLocalStorage(this.sessionInfo.userId)
      this.triggered = true
      if (res.length === 0) this.$toast('success', '没有更多记录了')
      if (this.messages.length <= 20 && res.length === 0) { //小于20条并且没有历史记录
        this.$toast('success', '没有更多记录了')
      } else if (res.length <= 20 && this.messages.length < 20) {// 小于20条并且有历史记录
        this.messages = [...res]
        if (res.length < 20) {
          this.$toast('success', '没有更多记录了')
        }
      } else {
        this.messages.unshift(...res)
      }
      setTimeout(() => {  //800毫秒后关闭刷新 
        this.triggered = false
      }, 800)
    },
    setItem2Storage (item) {
      this.messages.push(item);
      setLocalStorage(this.sessionInfo.userId, item)
    },
    previewImage (url) {
      this.previewImageUrl = url
      console.log("🚀 ~ file: professorChat.vue:99 ~ previewImage ~ this.previewImageUrl:", this.previewImageUrl)
      this.previewImageVisible = true
    },
    async sendMessage (msg, type) {
      if (msg.trim() !== '') {
        // 判断是不是跟上一条消息距离时间大于五分钟，大于就显示时间
        const nowStamp = Date.now()
        const lastStamp = this.messages.length > 0 ? this.messages[this.messages.length - 1].timestamp : ''
        const time = isShowTime(lastStamp, nowStamp)
        const msgItem = {
          msg: msg || this.newMessage,
          timestamp: nowStamp,
          isReceived: false,
          time: time
        }
        this.setItem2Storage(msgItem)
        this.send({
          "userId": this.sessionInfo.userId,
          "userType": 2,
          "msg": msg || this.newMessage,
          "type": "msg"
        })
        // 清空输入框的内容
        this.newMessage = '';
        // 调用子组件的方法进行滚动到底部
        let scrollRef = this.$refs.scrollview.scrollBottom();
        // 获取input的焦点，然后阻止软键盘收起
        this.focusState = false
        this.$nextTick(() => {
          this.focusState = true
        })
      }
    },
    connect () {
      if (this.connected || this.connecting) {
        uni.showModal({
          content: '正在连接或者已经连接，请勿重复连接',
          showCancel: false,
        })
        return
      }
      this.connecting = true
      uni.showLoading({
        title: '连接中...',
      })
      uni.connectSocket({
        url: 'ws://192.168.1.30:9001/websocket',
        success: (res) => {
          // 这里是接口调用成功的回调，不是连接成功的回调，请注意
          console.log('uni.connectSocket success', res)

        },
        fail: (err) => {
          // 这里是接口调用失败的回调，不是连接失败的回调，请注意
          console.log('uni.connectSocket fail', err)
        },
      })
      uni.onSocketOpen((res) => {
        this.connecting = false
        this.connected = true
        uni.hideLoading()
        uni.showToast({
          icon: 'none',
          title: '连接成功',
        })
        console.log('onOpen', res)
      })
      uni.onSocketError((err) => {
        this.connecting = false
        this.connected = false
        uni.hideLoading()

        uni.showModal({
          content: '连接失败，可能是websocket服务不可用，请稍后再试',
          showCancel: false,
        })
        console.log('onError', err)
      })
      uni.onSocketMessage((res) => {
        this.msg = res.data
        if (this.msg === '{"type":"init"}') {
          this.send({
            "userId": this.sessionInfo.professorId,
            "userType": 1,
            "type": "init"
          })
        } else {
          res = JSON.parse(this.msg)
          this.setItem2Storage({
            msg: res.msg,
            timestamp: res.timestamp,
            isReceived: true
          })

        }
        this.$refs.scrollview.scrollBottom();
        console.log('onMessage', res)
      })
      uni.onSocketClose((res) => {
        this.connected = false
        this.msg = ''
        console.log('onClose', res)
      })
    },
    send (resData) {
      console.log('111', 111)
      uni.sendSocketMessage({
        data: JSON.stringify(resData),
        success: (res) => {
          console.log(res)
        },
        fail: (err) => {
          console.log(err)
        },
      })
    },
    close () {
      uni.closeSocket({
        code: 1000,
        reason: 'close reason from client',
        success: (res) => {
          console.log('uni.closeSocket success', res)
        },
        fail: (err) => {
          console.log('uni.closeSocket fail', err)
        },
      })
    },
    getUrl (e) {
      console.log("🚀 ~ file: chat.vue:235 ~ getUrl ~ e:", e)
      this.sendMessage(e, 'img')
    }
  },
};
</script>

<style lang="scss" scoped>
page {
  padding: 0;
}
.chat-container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: calc(100% - 45px);
}

.input-container {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #f5f5f7;
  /* position: fixed; */
  bottom: 0;
  left: 0;
  width: calc(100% - 20px);
  img {
    width: 34px;
    height: 34px;
  }
}

.chat-input {
  flex: 1;
  margin: 0 10px;
  padding: 5px 10px;
  border-radius: 5px;
  border: none;
  outline: none;
  background-color: #fff;
  // height: 32px;
  .voice {
    width: 100%;
  }
}

.send-button {
  margin-left: 10px;
  border-radius: 15px;
  background: #d7ae3c;
  color: #fff;
  border: none;
  outline: none;
  padding: 0px 15px;
  font-size: 17px;
  height: 32px;
}
</style>